﻿namespace MobileTrack.Core.Data
{
    using System.Collections.Generic;
    using System.Data.Entity;
    using System.Linq;
    using MobileTrack.Core.Model;

    public class Repository<TEntity> : IRepository<TEntity>
        where TEntity : BaseEntity
    {
        private readonly IDbSet<TEntity> dataSet;

        public Repository(IDbSet<TEntity> dataSet)
        {
            this.dataSet = dataSet;
        }

        public IQueryable<TEntity> All
        {
            get
            {
                return this.dataSet;
            }
        }

        public void Add(TEntity entity)
        {
            this.dataSet.Add(entity);
        }

        public void AddRange(IEnumerable<TEntity> entities)
        {
            if (entities != null)
            {
                foreach (var entity in entities)
                {
                    this.Add(entity);
                }
            }
        }

        public void Delete(long id)
        {
            TEntity entityToDelete = this.dataSet.Find(id);
            this.Delete(entityToDelete);
        }

        public void Delete(TEntity entity)
        {
            this.dataSet.Remove(entity);
        }

        public void DeleteRange(IEnumerable<TEntity> entities)
        {
            if (entities != null)
            {
                foreach (var entity in entities)
                {
                    this.Delete(entity);
                }
            }
        }
    }
}
